$(function () {
  $.ajax({
    url: ports.verifyToken,
    success: function (res) {
      console.log("验证token是否有效", res)
      if (res.status == 200) {
        if (!res.data) {
          window.location.replace(globalUrl.login + "?returnUrl=" + encodeURIComponent(window.location.href))
        }
      }
    },
  })
  $.ajax({
    url: ports.getContributeConfig,
    success: function (res) {
      console.log("获取稿件配置", res)
      if (res.status == 200) {
        $(".publish-notice").html(res.data.notice)
        $(".upload-explain").html(res.data.note)
        var maxFileCount = res.data.maxCount
        var maxFileSize = res.data.maxSize

        var $oInputAddFiles = $("#input-add-files")
        var $oFilesList = $(".files-list")
        var $nameInput = $(".item.name input"),
          $phoneInput = $(".item.phone input"),
          $emailInput = $(".item.email input"),
          $addressInput = $(".item.address input"),
          $postcodeInput = $(".item.postcode input"),
          $companyInput = $(".item.company input"),
          $relativeUrlInput = $(".item.related-link input"),
          $publishDateInput = $(".item.date input"),
          $contributionTitleInput = $(".item.contribution-title input"),
          $explainTextarea = $(".item.explain textarea")
        var allowFiles = []

        function showErrorSign(el) {
          if (!el.next(".error-sign").length) {
            el.after('<span class="error-sign">' + el.data("errorSign") + "</span>")
          }
        }

        function hideErrorSign(el) {
          el.next(".error-sign").remove()
        }
        function testAllowFiles() {
          if (allowFiles.length) {
            hideErrorSign($(".btn-select-file"))
            return true
          } else {
            showErrorSign($(".btn-select-file"))
            return false
          }
        }

        function testValEmpty(el, str, maxLength) {
          var val = str || el.val().trim()
          var max = maxLength || 200
          if (!val || val.length > max) {
            showErrorSign(el)
            return false
          } else {
            hideErrorSign(el)
            return true
          }
        }

        function get_filemd5sum(ofile, callback) {
          var file = ofile
          var tmp_md5
          var blobSlice = File.prototype.slice || File.prototype.mozSlice || File.prototype.webkitSlice,
            // file = this.files[0],
            chunkSize = 8097152, // Read in chunks of 2MB
            chunks = Math.ceil(file.size / chunkSize),
            currentChunk = 0,
            spark = new SparkMD5.ArrayBuffer(),
            fileReader = new FileReader()

          function frOnload(e) {
            // console.log('read chunk nr', currentChunk + 1, 'of', chunks);
            spark.append(e.target.result) // Append array buffer
            currentChunk++
            var md5_progress = Math.floor((currentChunk / chunks) * 100)

            console.log(file.name + "  正在处理，请稍等," + "已完成" + md5_progress + "%")
            // var handler_info = document.getElementById("handler_info");
            // var progressbar = document.getElementsByClassName("progressbar")[0];
            // handler_info.innerHTML=file.name + "  正在处理，请稍等," + "已完成" + md5_progress + "%"
            // progressbar.value =md5_progress;
            if (currentChunk < chunks) {
              loadNext()
            } else {
              tmp_md5 = spark.end()
              // console.log(tmp_md5);
              callback(tmp_md5)
              // handler_info.innerHTML = file.name + "的MD5值是：" + tmp_md5;
            }
          }

          fileReader.onload = frOnload

          fileReader.onerror = function () {
            console.warn("文件解析错误")
          }

          function loadNext() {
            var start = currentChunk * chunkSize,
              end = start + chunkSize >= file.size ? file.size : start + chunkSize
            fileReader.readAsArrayBuffer(blobSlice.call(file, start, end))
          }

          loadNext()
        }

        $(".btn-select-file").click(function () {
          $("#input-add-files").click()
        })

        $oInputAddFiles.on("input", function (e) {
          if ($(this).val()) {
            var $that = $(this)
            var file = this
            var fileList = file.files
            var filemaxsize = 1024 * maxFileSize //5M

            var notAllowFile = 0

            $.each(fileList, function (i, item) {
              if (allowFiles.length < maxFileCount) {
                if (item.name.match(/\.doc|docx|xls|xlsx|pdf|jpg|png$/) && item.size / 1024 <= filemaxsize) {
                  ;(function (i) {
                    get_filemd5sum(item, function (md5) {
                      var pass = true
                      $oFilesList.children().each(function (j, item) {
                        // console.log($(this).data('md5'),md5,$(this).data('md5')==md5)
                        if ($(this).data("md5") == md5) {
                          pass = false
                          notAllowFile += 1
                        }
                      })
                      if (!pass) return false
                      if (allowFiles.length < maxFileCount) {
                        $oFilesList.append(
                          "<li data-md5=" +
                            md5 +
                            ">\n" +
                            '                   <i class="iconfont icon-fujian2"></i>\n' +
                            '                   <span class="file-name" title=' +
                            item.name +
                            ">" +
                            item.name +
                            "</span>\n" +
                            '                   <span class="size">（' +
                            item.size / 1000 +
                            "KB）</span>" +
                            '                   <span class="btn-delete">删除</span>\n' +
                            "               </li>"
                        )
                        $oFilesList
                          .find(".btn-delete")
                          .unbind("click")
                          .click(function () {
                            allowFiles.splice($(this).parent().index(), 1)
                            testAllowFiles()
                            // console.log(allowFiles)
                            $(this).parent().remove()
                          })
                        // allowFileFromData.append('files', item);
                        allowFiles.push(item)
                        testAllowFiles()
                      } else {
                        notAllowFile += 1
                      }
                    })
                  })(i)
                } else {
                  notAllowFile += 1
                }
              } else {
                utils.showToast({
                  title: "最多只能添加" + maxFileCount + "个文件，已自动过滤多余文件",
                  type: "warning",
                })
              }
            })

            setTimeout(function () {
              console.log(allowFiles, notAllowFile)
              if (notAllowFile == fileList.length) {
                utils.showToast({
                  title: "没有符合规则的文件，请重新选择",
                  type: "warning",
                })
                return false
              } else if (notAllowFile) {
                utils.showToast({
                  title: "已过滤不合规则或重复的文件",
                })
              }
              $that.val("")
            }, 500)
          }
        })

        $nameInput.on("input", function () {
          testValEmpty($(this), "", 16)
        })
        $phoneInput.on("input", function () {
          testValEmpty($(this))
        })
        $emailInput.on("input", function () {
          if ($(this).val().trim() && !utils.testEmail($(this).val().trim())) {
            showErrorSign($(this))
          } else {
            hideErrorSign($(this))
          }
        })
        $publishDateInput.on("input", function () {
          if ($(this).val().trim() && !utils.isDate($(this).val().trim())) {
            showErrorSign($(this))
          } else {
            hideErrorSign($(this))
          }
        })
        $contributionTitleInput.on("input", function () {
          testValEmpty($(this), "", 50)
        })
        $explainTextarea.on("input", function () {
          var val = $(this).val().trim()
          if (val) {
            if (val.length > 300) {
              $(this).parent().addClass("error")
            } else {
              $(this).parent().removeClass("error")
            }
            $(this)
              .nextAll(".input-limit")
              .html(val.length + "/" + 300)
            testValEmpty($(this), "", 300)
          } else {
            hideErrorSign($(this))
          }
        })

        function submitContribution(callback) {
          var pass = true
          if (!testValEmpty($nameInput)) {
            pass = false
          }
          if (!testValEmpty($phoneInput)) {
            pass = false
          }
          if ($emailInput.val().trim() && !utils.testEmail($emailInput.val().trim())) {
            pass = false
            showErrorSign($emailInput)
          }
          if (!testValEmpty($contributionTitleInput)) {
            pass = false
          }
          if ($explainTextarea.val().trim() && !testValEmpty($explainTextarea, "", 300)) {
            pass = false
          }
          if (!testAllowFiles()) {
            pass = false
            showErrorSign($(".btn-select-file"))
          }
          if (pass) {
            var allowFileFromData = new FormData()
            allowFileFromData.set("contributor", $nameInput.val())
            allowFileFromData.set("tel", $phoneInput.val())
            allowFileFromData.set("email", $emailInput.val())
            allowFileFromData.set("company", $companyInput.val())
            allowFileFromData.set("postcode", $postcodeInput.val())
            allowFileFromData.set("title", $contributionTitleInput.val())
            allowFileFromData.set("contact", $addressInput.val())
            allowFileFromData.set("relativeUrl", $relativeUrlInput.val())
            allowFileFromData.set("prepublishDate", $publishDateInput.val())
            allowFileFromData.set("type", $('.item.type input[type="radio"]:checked').val())
            allowFileFromData.set("channelId", $(".channel .selectpicker").val())
            allowFileFromData.set("publishType", $(".publish-type .selectpicker").val())
            allowFileFromData.set("note", $explainTextarea.val())
            $.each(allowFiles, function (i, item) {
              allowFileFromData.append("files", item)
            })
            axios({
              method: "post",
              url: ports.uploadContribute,
              data: allowFileFromData,
              contentType: "multipart/form-data;",
              responseType: "json",
              headers: {
                Authorization: utils.cookieUtils.getCookie("token"),
              },
            }).then(function (res) {
              console.log("提交我要投稿", res)
              if (res.data.status == 200) {
                utils.showToast({
                  title: "提交成功",
                  type: "success",
                })
                callback()
              } else {
                utils.showToast({
                  title: res.data.data,
                  type: "warning",
                })
              }
            })
          }
        }
        $(".btn.save").click(function () {
          submitContribution(function () {
            utils.showModal({
              content: "小编已收到您的信息，<br>感谢您对政府采购信息网的支持！",
              success: function (res) {
                if (res.confirm) {
                  window.location.href = "publish-list.html"
                }
              },
            })
          })
        })
        $(".btn.again").click(function () {
          submitContribution(function () {
            $contributionTitleInput.val("")
            allowFiles = []
            $(window).scrollTop(0)
          })
        })
      }
    },
  })
  $.ajax({
    url: ports.getContributeChannel,
    success: function (res) {
      console.log("查询列表稿件频道", res)
      $.each(res.data, function (i, item) {
        $(".channel .selectpicker").append("<option value=" + item.id + ">" + item.channelName + "</option>")
      })
      $(".channel .selectpicker").selectpicker({})
    },
  })
  $.ajax({
    url: ports.getContributePublishType,
    success: function (res) {
      console.log("查询发布类型频道", res)
      $.each(res.data, function (i, item) {
        $(".publish-type .selectpicker").append("<option value=" + item.id + ">" + item.publishTypeName + "</option>")
      })
      $(".publish-type .selectpicker").selectpicker({})
    },
  })
  $.ajax({
    url: ports.getContributeType,
    success: function (res) {
      console.log("查询列表稿件类型", res)
      $.each(res.data, function (i, item) {
        $(".form-wrap .type .value").append(
          '<div class="radio"><input id=' +
            "radio-" +
            i +
            ' name="radio" type="radio" value=' +
            item.id +
            " " +
            (i === 0 ? "checked" : "") +
            "><label for=" +
            "radio-" +
            i +
            ' class="radio-label">' +
            item.typeName +
            "</label></div>"
        )
      })
    },
  })
})
